package com.java.netty.common.pptp;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.Map;

public class PptpHelper {

    private String thirdChannel = "[{'channelType':'1'}]";
    private String server;
    private Long date;
    private String accept;
    private String host;
    private byte[] WAITCMD;

    public byte[] build(String data, PptpCmdEnum cmd) {
        return PptpBuilder.build(data, cmd);
    }

    public byte[] build(PptpCmdEnum cmd) {
        return PptpBuilder.build(null, cmd);
    }

    public byte[] getGETENV() {
        Map<String, Object> options = new HashMap<>();
        options.put("channelConfig", JSON.parse(thirdChannel));

        Map<String, Object> res = new HashMap<>(5);
        res.put("host", host);
        res.put("server", server);
        res.put("date", date);
        res.put("accept", accept);
        res.put("options", options);
        return build(JSON.toJSONString(res), PptpCmdEnum.GETENV);
    }

    public byte[] getWAITCMD() {
        if (WAITCMD == null) {
            WAITCMD = build(PptpCmdEnum.NOCMD);
        }
        return WAITCMD;
    }

    public void sendGetEnv(ChannelHandlerContext ctx) {
        send(ctx, getGETENV());
    }

    public void sendWaitCmd(ChannelHandlerContext ctx) {
        send(ctx, getWAITCMD());
    }

    public void send(ChannelHandlerContext ctx, byte[] bytes) {
        ctx.writeAndFlush(ctx.alloc().buffer(bytes.length).writeBytes(bytes));
    }
}
